const mysql = require('mysql');
const { MYSQL_CONFIG } = require('../config/db');

// 创建连接对象
const connection = mysql.createConnection(MYSQL_CONFIG);

// 开始连接
connection.connect();

// // 执行sql语句,查询
// const sqlSelect = `select * from blogs`;
// connection.query(sqlSelect, (err, result) => {
//     if(err){
//         console.error(err);
//         return;
//     }
//     console.log('result', result);
// });
/*
运行结果
result [
  RowDataPacket {
    id: 1,
    title: '标题3',
    content: '内容1',
    author: 'zhangsan',
    createdAt: 1234567890123,
    state: 1
  },
  RowDataPacket {
    id: 4,
    title: '标题2',
    content: '内容2',
    author: 'zhangsan',
    createdAt: 1234567890666,
    state: 0
  }
]
*/

// // 执行sql语句，添加
// const sqlSave = `insert into blogs (title, content, author, createdAt) values ('标题5','内容5', 'lisi', 1234567890111);`;
// connection.query(sqlSave, (err, result) => {
//     if(err){
//         console.error(err);
//         return;
//     }
//     console.log('result', result);
// });
/*
运行结果
result OkPacket {
  fieldCount: 0, 
  affectedRows: 1,
  insertId: 5,
  serverStatus: 2,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0
}
*/

// 执行sql语句，更新
// const sqlUpdate = `update blogs set title = '标题9' where content = '内容1';`;
// connection.query(sqlUpdate,(err, result) => {
//     if(err){
//         console.error('error', err);
//         return;
//     }
//     console.log('result', result);
// });
/*
执行结果
result OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 34,
  warningCount: 0,
  message: '(Rows matched: 1  Changed: 1  Warnings: 0',
  protocol41: true,
  changedRows: 1
}
*/

// 执行sql语句，删除
// const sqlDelete = `delete from blogs where title = '标题5'`;
// connection.query(sqlDelete, (err, result) => {
//     if(err){
//         console.error('error', err);
//         return;
//     }
//     console.log('result', result);
// });
/*
运行结果
result OkPacket {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  serverStatus: 34,
  warningCount: 0,
  message: '',
  protocol41: true,
  changedRows: 0
}
*/

// 关闭连接
//connection.end();

// function execSQL(sql, callback) {
//     connection.query(sql, callback);
// }

// 把函数改为promise形式
function execSQL(sql){
    const promise = new Promise((resolve, reject) =>{
        connection.query(sql,(err, result) => {
            if(err){
                reject(err);
                return;
            }
            resolve(result);
        });
    })

    return promise;
}

module.exports = {
    execSQL
}